package com.minyifang.wcspf.work.ui.widgets;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.utils.LogUtil;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadPackageDialog extends Dialog {


    public DownloadPackageDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    public static class Builder {
        private Context mContext;
        private String mTitle;
        private String mContent;
        private String mUrl;
        private Listener mListener;

        private DownloadPackageDialog mDialog;
        private TextView mTvTitle;
        private TextView mTvDownload;
        private boolean mIsDownloading;

        public Builder(Context context) {
            mContext = context;
        }

        public Builder setTitle(String title) {
            mTitle = title;
            return this;
        }

        public Builder setContent(String content) {
            mContent = content;
            return this;
        }

        public Builder setUrl(String url) {
            mUrl = url;
            return this;
        }

        public Builder setListener(Listener listener) {
            mListener = listener;
            return this;
        }

        public DownloadPackageDialog build() {
            mDialog = new DownloadPackageDialog(mContext, android.R.style.Theme_Dialog);
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            mDialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
            View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_update, null);
            mDialog.setContentView(layout);

            mTvTitle = layout.findViewById(R.id.tv_title_custom_dialog);
            WebView webView = layout.findViewById(R.id.wv_update);

            mTvDownload = layout.findViewById(R.id.tv_download);
            mTvDownload.setOnClickListener(v -> {
                if (!mIsDownloading) {
                    if (TextUtils.isEmpty(mUrl)) {
                        Toast.makeText(mContext, "下载地址为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!mUrl.startsWith("http") || !mUrl.toLowerCase().contains("apk"))
                        if (mListener != null) {
                            mListener.urlMayNotAApkFile(mDialog, mUrl);
                            return;
                        }
                    mTvDownload.setText("任务准备中...");
                    new DownLoadAsyncTask().execute(mUrl);
                    mDialog.setCancelable(false);
                    mIsDownloading = true;
                }
            });

            //设置标题和内容
            if (mTitle != null) mTvTitle.setText(mTitle);
            if (mContent != null) webView.loadData(mContent, "text/html;charset=UTF-8", null);
            return mDialog;
        }

        public void show(boolean isCancelable) {
            DownloadPackageDialog dialog = build();
            dialog.setCancelable(isCancelable);
            dialog.show();
        }

        @SuppressLint("StaticFieldLeak")
        private class DownLoadAsyncTask extends AsyncTask<String, Integer, File> {
            @Override
            protected File doInBackground(String... strings) {
                URL url;
                HttpURLConnection urlConnection = null;
                InputStream inputStream = null;
                OutputStream outputStream = null;
                File apk = new File(Environment.getExternalStorageDirectory(), "apk");
                if (apk.isFile())
                    apk.delete();
                if (!apk.exists())
                    apk.mkdir();
                File file = new File(apk, "wcs.apk");
                if (file.exists())
                    file.delete();
                try {
                    url = new URL(strings[0]);
                    outputStream = new FileOutputStream(file);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setDoInput(true);
                    urlConnection.setRequestMethod("GET");
                    urlConnection.connect();
                    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        int length = urlConnection.getContentLength();
                        inputStream = urlConnection.getInputStream();
                        byte[] bytes = new byte[8096];
                        int downloadedLength = 0;
                        int readLength;
                        while ((readLength = inputStream.read(bytes)) != -1) {
                            downloadedLength += readLength;
                            publishProgress(downloadedLength, length);
                            outputStream.write(bytes, 0, readLength);
                        }
                        outputStream.flush();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    close(outputStream);
                    close(inputStream);
                    if (urlConnection != null)
                        urlConnection.disconnect();
                }
                return file;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mTvDownload.setText(String.format("已下载%s%%", ((int) (values[0] * 1f / values[1] * 100))));
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
            }

            @Override
            protected void onPostExecute(File file) {
                if (file.exists() && mListener != null) {
                    mListener.onDownloadComplete(mDialog, file);
                }
                LogUtil.e("下载完成", file.getAbsolutePath());
            }

            private void close(Closeable closeable) {
                try {
                    if (closeable != null)
                        closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public interface Listener {
            void urlMayNotAApkFile(Dialog dialog, String url);

            void onDownloadComplete(Dialog dialog, File file);
        }
    }

}
